package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        // 获取文件输入流
        InputStream inputStream = file.getInputStream();

        String date = new DateTime().toString("yyyy/MM/dd/");
        String filenameExtension = StringUtils.getFilenameExtension(file.getOriginalFilename());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = date + uuid + "." + filenameExtension;

        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(fileName)  // 存储至minio中的文件名
                .stream(inputStream, inputStream.available(), -1)  // 文件流，文件大小，文件类型
                .build());


        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
    }
}
